﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Reflection;
//MicroDesigner
using Jc.MicroDesigner.Objects;
using Jc.MicroDesigner.ElementsLib;
using Jc.MicroDesigner.Drawings.Tools;
using Jc.MicroDesigner.Drawings;
using Jc.MicroDesigner.Management;
using Jc.MicroDesigner.ToolWindows;

namespace Jc.MicroDesigner
{
    /// <summary>
    /// Главная форма приложения
    /// </summary>
    public partial class MainForm : Form
    {
        private CompositeElement _CompositeObject = null;
        private ObjectManager _Manager = new ObjectManager();
        private ToolBoxObject _Tools = null;

        /// <summary>
        /// Конструктор формы
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            _Manager.AppPath = Application.StartupPath;
            _Manager.Author = System.Environment.UserName;
            _Manager.TicPerTact = 8;
            _Manager.TactCount = 16;

            //Сборки, содержащие объекты схемы
            SchemeSerializer.Assemblies.AddRange(
                new System.Reflection.Assembly[]
                {
                    typeof(ObjectManager).Assembly,
                    typeof(ToolBoxObject).Assembly,
                    typeof(AND2).Assembly
                });
            SchemeSerializer.AppPath = _Manager.AppPath;

            _Tools = new ToolBoxObject(_Manager, _Manager.AppPath + "Config\\toolbox.xml");
            _Tools.Canvas = SchemeCanvas;
            _Tools.PopulateListView(ToolList);
            _Tools.PopulateToolStrip(ToolMenu);
            SchemeCanvas.ToolBox = _Tools;
            SchemeCanvas.ObjManager = _Manager;

            _Manager.SchemeCanvas.Width = SchemeCanvas.Width;
            _Manager.SchemeCanvas.Height = SchemeCanvas.Height;
        }

        #region Menu Events

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void тестыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TestForm tst = new TestForm();
            tst.Show();
        }

        private void очиститьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Manager.Elements.Clear();
            SchemeCanvas.Invalidate();
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MicroDesignerAbout about = new MicroDesignerAbout();
            about.ShowDialog();
        }

        private void списокНаблюденияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WatchListForm wl = new WatchListForm();
            wl.Show(_Manager);
        }

        private void запуститьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StartItForm form = new StartItForm();
            form.Show(_Manager);
        }

        private void генераторыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SignalsEditorForm form = new SignalsEditorForm();
            form.Show(_Manager);
        }

        private void сохранитьСхемуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool saved = true;
            try
            {
                if (String.IsNullOrEmpty(_Manager.SchemeFile))
                {
                    if (SaveSchemeDialog.ShowDialog() == DialogResult.OK)
                    {
                        _Manager.SchemeFile = SaveSchemeDialog.FileName;
                        SchemeSerializer.SaveSheme(_Manager).Save(_Manager.SchemeFile);
                    }
                    else
                        saved = false;
                }
                else
                {
                    SchemeSerializer.SaveSheme(_Manager).Save(_Manager.SchemeFile);
                }
            }
            catch (Exception ex)
            {
                saved = false;
                Exceptions.ExceptionDialog.ShowException(ex, "Ошибка сохранения", ex.Message);
            }
            if (saved)
            {
                MessageBox.Show("Схема успешно сохранена", "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void загрузитьСхемуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (OpenSchemeDialog.ShowDialog() == DialogResult.OK)
            {
                bool loaded = true;
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(OpenSchemeDialog.FileName);
                    _Manager = SchemeSerializer.LoadSheme(doc);
                    _Manager.SchemeFile = OpenSchemeDialog.FileName;
                    SchemeCanvas.Init(_Manager);
                }
                catch (Exception ex)
                {
                    loaded = false;
                    Exceptions.ExceptionDialog.ShowException(ex, "Ощибка загрузки", ex.Message);
                }
                if (loaded)
                {
                    MessageBox.Show("Схема успешно загружена", "Загрузка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void создатьСхемуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Manager = new ObjectManager();
            _Manager.AppPath = Application.StartupPath;
            _Manager.Author = System.Environment.UserName;

            _Manager.SchemeCanvas.Width = SchemeCanvas.Width;
            _Manager.SchemeCanvas.Height = SchemeCanvas.Height;

            SchemeCanvas.Init(_Manager);
        }

        private void редакторЭлементаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContainerEditorForm editor = new ContainerEditorForm(_CompositeObject);
            editor.ShowDialog(_Manager);
        }

        private void генераторыИмпульсовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClockEditor editor = new ClockEditor();
            editor.Show(_Manager);
        }

        private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO: придумать механизм выделения объектов на холсте
            SchemeCanvas.DeleteSelectedObject();
        }

        private void свойстваХолстаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SchemeCanvas.ShowCanvasProperties();
        }

        private void свойстваСхемыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SchemePropertiesForm form = new SchemePropertiesForm();
            form.ShowDialog(_Manager);
        }

        private void руководствоToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HelpViewer form = new HelpViewer();
            form.ShowHelp();
        }

        private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool saved = true;
            try
            {
                if (SaveSchemeDialog.ShowDialog() == DialogResult.OK)
                {
                    _Manager.SchemeFile = SaveSchemeDialog.FileName;
                    SchemeSerializer.SaveSheme(_Manager).Save(_Manager.SchemeFile);
                }
                else
                    saved = false;
            }
            catch (Exception ex)
            {
                saved = false;
                Exceptions.ExceptionDialog.ShowException(ex, "Ошибка сохранения", ex.Message);
            }
            if (saved)
            {
                MessageBox.Show("Схема успешно сохранена", "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void сохранитьИзображениеСхемыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SavePictDialog.ShowDialog() == DialogResult.OK)
            {
                SchemeCanvas.SaveImage(SavePictDialog.FileName);
            }
        }

        #endregion
    }
}